package com.kmproject.haifu.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.blankj.utilcode.util.StringUtils;
import com.flyco.roundview.RoundTextView;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.utils.CustomGridItemDecoration;
import com.kmproject.haifu.app.utils.ViewExtensionKt;
import com.kmproject.haifu.di.component.DaggerPersonalHpRentingListComponent;
import com.kmproject.haifu.di.module.PersonalHpRentingListModule;
import com.kmproject.haifu.mvp.contract.PersonalHpRentingListContract;
import com.kmproject.haifu.mvp.model.entity.beans.HouseRentListShowBean;
import com.kmproject.haifu.mvp.model.entity.beans.HouseRentListShowInfoBean;
import com.kmproject.haifu.mvp.model.entity.beans.ScreenData;
import com.kmproject.haifu.mvp.model.entity.resbean.ReqParamsQureyHouseRentListByStoreId;
import com.kmproject.haifu.mvp.presenter.PersonalHpRentingListPresenter;
import com.kmproject.haifu.mvp.ui.adapter.BaseRecyclerAdapter;
import com.kmproject.haifu.mvp.ui.holder.SmartViewHolder;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.OnRefreshLoadMoreListener2;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.PullToRefreshView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.util.List;
import java.util.Objects;

import butterknife.BindView;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * 用户主页{icon_home_category_2}
 */
public class PersonalHpRentingListFragment extends BaseFragment<PersonalHpRentingListPresenter> implements PersonalHpRentingListContract.View {
    @BindView(R.id.srl_personal_hp_bis_data)
    PullToRefreshView srlPersonalHpBisData;
    @BindView(R.id.rv_personal_hp_bis_data)
    RecyclerView rvPersonalHpBisData;
    @BindView(R.id.i_empty)
    View empty;
    private int page = 1;
    private static final String USER_ID = "userId";
    private static final String ACCOUNT_TYPE = "accountType";
    private String userId;
    private int accountType;
//    private UserBean userBean;//获取用户信息
    private String houseCategory;

    private BaseRecyclerAdapter<HouseRentListShowInfoBean> adapter;
    private ReqParamsQureyHouseRentListByStoreId reqParamsQureyHouseRentListByStoreId;//根据店铺查询租房列表

    /**
     * @param userId      accountType传入0时，userId为用户id；accountType传入1时，userId为店铺id
     * @param accountType 账号类型0-用户；1-店铺
     * @return
     */
    public static PersonalHpRentingListFragment newInstance(String userId, int accountType) {
        PersonalHpRentingListFragment fragment = new PersonalHpRentingListFragment();
        Bundle args = new Bundle();
        args.putString(USER_ID, userId);
        args.putInt(ACCOUNT_TYPE, accountType);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(AppComponent appComponent) {
        DaggerPersonalHpRentingListComponent
                .builder()
                .appComponent(appComponent)
                .personalHpRentingListModule(new PersonalHpRentingListModule(this))//请将PersonalHpBisDataModule()第一个首字母改为小写
                .build()
                .inject(this);
    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_personal_hp_renting_list, container, false);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
//        userBean = DataHelper.getDeviceData(getContext(), AppConstant.USER_INFO);//获取用户信息
        if (getArguments() != null) {
            userId = getArguments().getString(USER_ID);
            accountType = getArguments().getInt(ACCOUNT_TYPE);
        }

        rvPersonalHpBisData.addItemDecoration(new CustomGridItemDecoration.Builder(Objects.requireNonNull(getContext())).setVerticalSpan(0f).
                setHorizontalSpan(1f).setColor(ContextCompat.getColor(getContext(), R.color.common_menu_text)).setShowLastLine(false).build());
        ArmsUtils.configRecyclerView(rvPersonalHpBisData, new LinearLayoutManager(getContext()));
        rvPersonalHpBisData.setItemAnimator(new DefaultItemAnimator());
        srlPersonalHpBisData.setEnableRefresh(true);
        srlPersonalHpBisData.setEnableAutoLoadMore(false);
        srlPersonalHpBisData.setEnableHeaderTranslationContent(true);

        adapter = new BaseRecyclerAdapter<HouseRentListShowInfoBean>(R.layout.item_personal_hp_house) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, HouseRentListShowInfoBean model, int position) {
                holder.image(R.id.personal_hp_imv_house_img, model.getAvatar());
                String sb1 = model.getRentTypeName() + "." + model.getRoomCountName() + model.getDrawingCountName() +
                        "." + model.getToiletCountName() + "." + model.getHouseName();
                holder.text(R.id.personal_hp_imv_house_desc_1, sb1);
                String sb2 = model.getAcreage() + "m²" + " " + model.getFloorName() + "/" + model.getTotalFloorName() +
                        " " + model.getAddressDetail();
                holder.text(R.id.personal_hp_imv_house_desc_2, sb2);
                holder.text(R.id.personal_hp_tv_price, model.getFormatMonthRent());
                LinearLayout llUniqueFeature = (LinearLayout) holder.findViewById(R.id.ll_unique_feature);//特色

                List<HouseRentListShowBean.DetailsBean> detailsBeans = model.getDetails();
                if (detailsBeans != null && detailsBeans.size() > 0) {
                    llUniqueFeature.setVisibility(View.VISIBLE);
                    llUniqueFeature.removeAllViews();
                    RoundTextView roundTextView;
                    for (HouseRentListShowBean.DetailsBean db : detailsBeans) {
                        roundTextView = (RoundTextView) LayoutInflater.from(getContext()).inflate(R.layout.room_feature, null);
//                        roundTextView.getDelegate().setCornerRadius(ConvertUtils.dp2px(5));
//                        roundTextView.getDelegate().setStrokeColor(ContextCompat.getColor(getContext(), R.color.color_F9D35A));
//                        roundTextView.getDelegate().setStrokeWidth(ConvertUtils.dp2px(1));
//                        roundTextView.setTextColor(ContextCompat.getColor(getContext(), R.color.color_747474));
//                        roundTextView.setPadding(5, 3, 5, 3);
//                        roundTextView.setLines(1);
//                        roundTextView.setGravity(Gravity.CENTER);
                        roundTextView.setText(db.getBaseDictName());
                    }
                } else {
                    llUniqueFeature.setVisibility(View.GONE);
                }
                if (!StringUtils.isEmpty(model.getOriginalBusinessName())) {
                    holder.findViewById(R.id.personal_hp_tv_economic_company_name).setVisibility(View.VISIBLE);
                    holder.text(R.id.personal_hp_tv_economic_company_name, model.getOriginalBusinessName());
                } else {
                    holder.findViewById(R.id.personal_hp_tv_economic_company_name).setVisibility(View.GONE);
                }
            }
        };
        rvPersonalHpBisData.setAdapter(adapter);

        adapter.setOnItemClickListener((parent, view, position, id) -> {
            ArmsUtils.makeText(getContext(), "index:" + adapter.getRealItemPosition(position));
        });

        srlPersonalHpBisData.setOnRefreshLoadMoreListener2(new OnRefreshLoadMoreListener2() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout, int curPageNo) {
                page = curPageNo;
                getHouseRentList();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout, int curPageNo) {
                page = curPageNo;
                getHouseRentList();
            }
        });
    }

    private void getHouseRentList() {
        if (accountType == 0) {
            mPresenter.getHouseRentByUser(String.valueOf(page), userId, houseCategory);//"521677655146233856"
        } else {
            if (reqParamsQureyHouseRentListByStoreId == null) {
                reqParamsQureyHouseRentListByStoreId = new ReqParamsQureyHouseRentListByStoreId();
            }
            mPresenter.listHouseRent4Store(String.valueOf(page), userId, reqParamsQureyHouseRentListByStoreId);//"521677655146233856"
        }
    }

    /**
     * 此方法是让外部调用使fragment做一些操作的,比如说外部的activity想让fragment对象执行一些方法,
     * 建议在有多个需要让外界调用的方法时,统一传Message,通过what字段,来区分不同的方法,在setData
     * 方法中就可以switch做不同的操作,这样就可以用统一的入口方法做不同的事
     * <p>
     * 使用此方法时请注意调用时fragment的生命周期,如果调用此setData方法时onCreate还没执行
     * setData里却调用了presenter的方法时,是会报空的,因为dagger注入是在onCreated方法中执行的,然后才创建的presenter
     * 如果要做一些初始化操作,可以不必让外部调setData,在initData中初始化就可以了
     *
     * @param data
     */

    @Override
    public void setData(Object data) {
        if (data != null) {
            ScreenData sd = (ScreenData) data;
            houseCategory = sd.getCategoryId();
            if (accountType == 1) {
                if (reqParamsQureyHouseRentListByStoreId == null) {
                    reqParamsQureyHouseRentListByStoreId = new ReqParamsQureyHouseRentListByStoreId();
                    reqParamsQureyHouseRentListByStoreId.setHouseCategory(houseCategory);
                    reqParamsQureyHouseRentListByStoreId.setHouseArea(sd.getLocation());
                    reqParamsQureyHouseRentListByStoreId.setMinMonthRent(sd.getMinRenting());
                    reqParamsQureyHouseRentListByStoreId.setMaxMonthRent(sd.getMaxRenting());
                    // todo 其他条件待定
                }
            }
        }
        getHouseRentList();
    }

    @Override
    public void showLoading() {
        loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        loadingDialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
    }

    @Override
    public void showRentList(List<HouseRentListShowInfoBean> houseRentListShowInfoBeans) {
        srlPersonalHpBisData.finishRefresh();
        srlPersonalHpBisData.finishLoadMore();
        if (houseRentListShowInfoBeans != null && !houseRentListShowInfoBeans.isEmpty()) {
            ViewExtensionKt.visible(empty, false);
            ViewExtensionKt.visible(rvPersonalHpBisData, true);
            if (ViewExtensionKt.isPullDown(srlPersonalHpBisData, houseRentListShowInfoBeans.size(), page)) {
                adapter.refresh(houseRentListShowInfoBeans);
            } else {
                adapter.loadMore(houseRentListShowInfoBeans);
            }
        } else {
            if (page > 1) {
                ViewExtensionKt.visible(empty, false);
                ViewExtensionKt.visible(rvPersonalHpBisData, true);
            } else {
                ViewExtensionKt.visible(empty, true);
                ViewExtensionKt.visible(rvPersonalHpBisData, false);
            }
        }
    }

    @Override
    public void getListFailed() {
        if (page > 1) {
            page--;
        }
        srlPersonalHpBisData.finishLoadMore();
        srlPersonalHpBisData.finishRefresh();
    }
}